<template>
    <el-tabs
    :model-value="currentFullPath"
    type="card"
    class="star-tabs"
    tab-position="bottom"
    @tab-remove="handleRemove"
    @tab-change="handleChangeCurrentTab"
  >
    <el-tab-pane
      v-for="(item, index) in menuStore.tabRouters"
      :label="item.title"
      :name="item.path"
      :key="`${item.path}_${index}`"
      :closable="!item.isHome"
    >
    <template #label>
      <el-dropdown trigger="contextmenu">
        <span class="tab-title">
          {{item.title}}
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="data in tabMenu" :key="data.name" :icon="data.icon" @click="onContextmenuItem(data.name, item, index)">
              {{data.label}}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
    </el-tab-pane>
  </el-tabs>
</template>
<script setup>
import useStore from '@/store'
import { reactive, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const tabMenu = reactive([
  { name: 'refresh', label: '重新加载', icon: 'Refresh' },
  { name: 'closeLeft', label: '关闭左侧', icon: 'ArrowLeftBold' },
  { name: 'closeRight', label: '关闭右侧', icon: 'ArrowRightBold' },
  { name: 'closeOther', label: '关闭其他', icon: 'SemiSelect' },
  { name: 'closeAll', label: '关闭全部', icon: 'CloseBold' }
])

const route = useRoute()
const router = useRouter()
const { menuStore } = useStore()

const currentFullPath = computed(() => {
  return menuStore.appendFullPath(route.path, route.query)
})

const handleChangeCurrentTab = (path) => {
  // const route = menuStore.tabRouters.filter(item => item.path === path)
  let routeIdx = 0
  let targetRoute = null
  menuStore.tabRouters.forEach((item, index) => {
    if (item.path === path) {
      targetRoute = item
      routeIdx = index
    }
  })

  handleRefresh(targetRoute, routeIdx)
}

const handleRemove = (targetName) => {
  const currentPath = menuStore.appendFullPath(route.path, route.query)
  const tabs = menuStore.tabRouters
  menuStore.subtractCurrentTabRouter({ path: targetName })

  if (currentPath === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.path === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          router.push({ path: nextTab.path, query: nextTab.query })
        }
      }
    })
  }
}

const onContextmenuItem = (name, menu, index) => {
  switch (name) {
    case 'refresh':
      handleRefresh(menu, index)
      break
    case 'closeLeft':
      closeLeft(menu.path, index)
      break
    case 'closeRight':
      closeRight(menu.path, index)
      break
    case 'closeOther':
      closeOtherTab(menu.path, index)
      break
    case 'closeAll':
      closeAllTab()
      break
  }
}

// 刷新
const handleRefresh = (targetRoute, routeIdx) => {
  // 相同路由push/replace不刷新，router-view监听isRefreshing，不同直接跳转.
  const currentFullPath = menuStore.appendFullPath(route.path, route.query)
  let newPath = targetRoute.path
  if (newPath.indexOf('?') > 0) {
    newPath = newPath.substr(0, newPath.indexOf('?'))
  }

  if (targetRoute.path === currentFullPath) {
    menuStore.toggleTabRouterAlive(routeIdx)
    nextTick(() => {
      menuStore.toggleTabRouterAlive(routeIdx)
    })
  } else if (newPath === route.path) {
    menuStore.toggleTabRouterAlive(routeIdx)
    router.replace({ path: newPath, query: targetRoute.query })
    nextTick(() => {
      menuStore.toggleTabRouterAlive(routeIdx)
    })
  } else {
    router.replace({ path: newPath, query: targetRoute.query })
  }
}

const closeLeft = (path, routeIdx) => {
  menuStore.subtractTabRouterLeft({ path, routeIdx })
  handleOperationEffect('left', routeIdx)
}

const closeRight = (path, routeIdx) => {
  menuStore.subtractTabRouterRight({ path, routeIdx })
  handleOperationEffect('right', routeIdx)
}

const closeOtherTab = (path, routeIdx) => {
  menuStore.subtractTabRouterOther({ path, routeIdx })
  handleOperationEffect('other', routeIdx)
}

const closeAllTab = () => {
  menuStore.subtractTabRouterAll()
  const nextRouter = menuStore.tabRouters
  if (nextRouter) {
    router.push({ path: nextRouter[0].path, query: nextRouter[0].query })
  }
}

const handleOperationEffect = (type, routeIdx) => {
  const currentPath = router.currentRoute.value.path
  const tabRouters = menuStore.tabRouters

  const currentIdx = tabRouters.findIndex(i => i.path === currentPath)

  const needRefreshRouter =
    (type === 'other' && currentIdx !== routeIdx) ||
    (type === 'left' && currentIdx < routeIdx) ||
    (type === 'right' && currentIdx === -1)

  if (needRefreshRouter) {
    const nextRouteIdx = type === 'right' ? tabRouters.length - 1 : 1
    const nextRouter = tabRouters[nextRouteIdx]
    router.push({ path: nextRouter.path, query: nextRouter.query })
  }
}

</script>
<style lang="scss" scoped>
// 右键样式取消，使用tab样式
.el-dropdown {
    color: unset;
    font-size: unset;
    line-height: unset;
    vertical-align: unset;
}
.star-tabs {
  // width: calc(100% - 60px - 400px);
  width: 100%;
  // display: flex;
}
</style>
